package cn.tedu.cs.baking.config;

import cn.tedu.cs.baking.common.ex.BusinessException;
import cn.tedu.cs.baking.response.AppCode;
import cn.tedu.cs.baking.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice(basePackages = {"cn.tedu.cs.baking.controller"})
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 功能描述:controller层的BindException被捕获统一处理为10002，"参数原因"
    */
    @ExceptionHandler({BindException.class})
    public JsonResult bindExceptionHandler(BindException e){
        // 从异常对象中拿到objectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new JsonResult(AppCode.VALIDATE_ERROR,objectError.getDefaultMessage());
    }

    /**
     * 功能描述: controller层的针对@RequestBody报出的异常拦截处理
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public JsonResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        // 从异常对象中拿到objectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new JsonResult(AppCode.VALIDATE_ERROR,objectError.getDefaultMessage());
    }

    /**
     * 功能描述: controller层的APIException被捕获统一返回
     */
    @ExceptionHandler(BusinessException.class)
    public JsonResult apiExceptionHandler(BusinessException e){
        log.error(e.getMessage(),e);
        return new JsonResult(e.getCode(),e.getMsg(),e.getMessage());
    }
}
